import { constantRoutes } from '@/router'
import { getRoleFunctionTree } from '@/api/admin'

/* Layout */
import Layout from '@/layout'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

/**
 * 解析权限关系树，生成功能的路由
 * @param {permis} 权限关系树信息
 */
function generateAsyncRoutes(permis) {
  return permis.map((item) => {
    const role_router = {
      path: item.path,
      name: item.name,
      component: Layout,
      meta: { title: item.title, icon: item.icon },
      children: []
    }
    if (item.nodeType) {
      item.children.map((child) => {
        let linkHidden = false
        if (child.isHidden) {
          linkHidden = true
        }
        role_router.children.push({
          path: child.path,
          name: child.name,
          hidden: linkHidden,
          // component: () => import(`@/views/${child.url}`),
          component: () => Promise.resolve(require(`@/views/${child.url}`).default),
          meta: { title: child.title, icon: child.icon }
        })
      })
    }
    return role_router
  })
}

const actions = {
  async generateRoutes({ commit }, roles) {
    return new Promise((resolve, reject) => {
      let accessedRoutes
      getRoleFunctionTree(roles).then(response => {
        const { data } = response
        accessedRoutes = generateAsyncRoutes(data) || []

        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)
      }).catch(error => {
        reject(error)
      })
      // if (roles.includes('admin')) {
      //   accessedRoutes = asyncRoutes || []
      // } else {
      //   accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      // }
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
